package com.kol.collect.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kol.collect.common.AjaxJson;
import com.kol.collect.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.kol.collect.exception.BusinessException;

import jdk.nashorn.internal.runtime.regexp.joni.exception.InternalException;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by liukun on 20/3/8.
 */
@Component
public class WebAuthInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LogManager.getLogger(WebAuthInterceptor.class.getName());
    @Autowired
    private JedisPool jedisPool;
    /**
     * web用户token过期时间
     */
    @Value("${user.token.expire}")
    private Integer userTokenExpire;

    @Override
    public boolean preHandle(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Object handler) throws Exception {
        // 地址过滤
        String uri = servletRequest.getRequestURI();
        if (uri.contains("/error")) {
            return false;
        }
        String username = servletRequest.getHeader(Constants.USER_NAME);
        String token = servletRequest.getHeader(Constants.USER_TOKEN);
        logger.info("username is: {} , token is: {}", username, token);
        setResponseHead(servletResponse);
        checkAuthentication(username, token);
        return true;
    }

    private void checkAuthentication(String username, String token) throws InternalException, BusinessException {
        Jedis jedis = jedisPool.getResource();
        try {
            if (StringUtils.isBlank(username)) {
                throw new BusinessException(AjaxJson.STATUS_USER_HEADER_NO_USER_NAME, AjaxJson.MSG_USER_HEADER_NO_USER_NAME);
            }
            if (StringUtils.isBlank(token)) {
                throw new BusinessException(AjaxJson.STATUS_USER_LOGIN_NO_TOKEN, AjaxJson.MSG_USER_LOGIN_NO_TOKEN);
            }
            List<String> fileds = jedis.hmget(Constants.WEB_USER_TOKEN + username, Constants.USER_NAME, Constants.USER_TOKEN);
            if (null == fileds || fileds.size() == 0 || !username.equals(fileds.get(0)) || !token.equals(fileds.get(1))) {
                throw new BusinessException(AjaxJson.STATUS_TOKEN_FAIL, AjaxJson.MSG_TOKEN_FAIL);
            }
            // 重置token时间
            jedis.expire(Constants.WEB_USER_TOKEN + username, userTokenExpire);
        } finally {
            jedis.close();
        }
    }

    private void setResponseHead(HttpServletResponse servletResponse) {
        servletResponse.setHeader("Access-Control-Allow-Origin", "*");
        servletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        servletResponse.setHeader("Access-Control-Max-Age", "3600");
        servletResponse.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-type, token, username");
    }

}